package com.ztc.util.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.ztc.util.NumberUitl;
import com.ztc.util.TextUtils;
import org.apache.log4j.Logger;

public final class SMSUtil {
    private static Logger logger = Logger.getLogger(SMSUtil.class);
    private static final String URL_API = "http://dxhttp.c123.cn/tx/?uid=500896530057&pwd=0192023A7BBD73250516F069DF18B500&mobile={mobile}&content={content}&encode=utf8";

    private SMSUtil() {
    }

    public static SMSResult send(String content, String... mobiles) {
        return send(content, TextUtils.join(mobiles, ","));
    }

    /**
     * @param content 发送内容
     * @param mobile  手机号
     * @return 是否发送成功
     */
    public static SMSResult send(String content, String mobile) {
        if (TextUtils.isEmpty(content) || TextUtils.isEmpty(mobile)) {
            return SMSResult.MOBILE_OR_OUTLINE_NULL;
        }
        logger.debug("mobile:" + mobile + "/content:" + content);
        try {
            String uri = URL_API.replace("{mobile}", String.join(",", mobile)).replace("{content}", URLEncoder.encode(content, "UTF-8"));
            URL url = new URL(uri);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine = in.readLine().toString();
            SMSResult t = SMSResult.parse(NumberUitl.parseInt(inputLine, 0));
            logger.debug(t.getText());
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 随机生成短信验证码.
     *
     * @param min 最小值
     * @param max 最大值
     * @return 验证码
     */
    public static int getRanNum(int min, int max) {
        int randNum = min + (int) (Math.random() * ((max - min) + 1));
        return randNum;
    }
}
